package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.entity.User;
import com.example.result.Code;
import com.example.result.Message;
import com.example.result.R;
import com.example.service.IUserService;
import com.example.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;

/**
 * @Date 2022/9/8
 * @Description
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping
    public R saveUser(@RequestBody User user) {
        boolean flag = userService.save(user);
        return R.success(flag, Message.ADD_USER_SUCCESS);
    }

    @DeleteMapping("/{ids}")
    public R deleteUser(@PathVariable List<Long> ids) {
        boolean flag = userService.removeByIds(ids);
        return R.success(flag, Message.DELETE_USER_SUCCESS);
    }

    @PutMapping
    public R updateUser(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        return R.success(flag, Message.UPDATE_USER_SUCCESS);
    }

    @GetMapping("/{currentPage}/{pageSize}")
    public R getUsers(@PathVariable int currentPage, @PathVariable int pageSize, User user) {
        IPage<User> page = userService.getUsers(currentPage, pageSize, user);
        if (currentPage > page.getPages()) {
            page = userService.getUsers((int) page.getPages(), pageSize, user);
        }
        return R.success(page, Message.GET_USER_SUCCESS);
    }

    @GetMapping("/{username}")
    public R getUser(@PathVariable String username) {
        return R.success(
                userService.getOne(new QueryWrapper<User>().eq("username", username)),
                Message.GET_USER_SUCCESS
        );
    }

    @PostMapping("/upload")
    public R upload(@RequestParam("imgFile") MultipartFile file) {
        System.out.println(file);
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffixName = originalFilename.substring(index - 1);
        String fileName = "bgblog-" + UUID.randomUUID().toString() + suffixName;
        try {
            // 上传到七牛云服务器
            QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail(Message.UPLOAD_AVATAR_SUCCESS);
        }
        return R.success(fileName, Message.UPLOAD_AVATAR_SUCCESS);
    }

    @GetMapping("/logout")
//    @RequiresAuthentication
    public R logout() {
//        SecurityUtils.getSubject().logout();
        return R.success(null, Message.LOGOUT_SUCCESS);
    }
}
